<template>
  <div class="wrap">
    <div class="addImg">
      <div>
        <img src="../assets/drawIMg.png" alt />
        <p>拖动到此区域插入图片</p>
      </div>
      <input type="file" @change="getImg" id="file" class="inpfile" />
    </div>
    <div class="goodsInfo">
      <div class="navListmax">
        <img :src="addImgUrl" alt />
        <div class="item">
          <span>规格</span>
          <el-input placeholder="请输入规格" maxlength="5" v-model.trim="addOrderparams.orderSize"></el-input>
        </div>
        <div class="item">
          <span>客户昵称</span>
          <el-autocomplete
            class="inline-input"
            v-model.trim="addOrderparams.customerName"
            :fetch-suggestions="querySearch"
            placeholder="请输入客户昵称"
            @select="customerNameSelect"
            :trigger-on-focus="false"
            popper-class="my-autocomplete"
          >
            <template slot-scope="{ item }">
              <div class="name">{{ item.value }}</div>
              <span class="addr">{{ item.phone }}</span>
            </template>
          </el-autocomplete>
        </div>
        <div class="item">
          <span>电话</span>
          <el-input placeholder="请输入电话" v-model.trim="addOrderparams.customerTel"></el-input>
        </div>
        <div class="item">
          <span>价格</span>
          <el-input
            placeholder="请输入价格"
            onkeyup="this.value=this.value.replace(/[^\d.]/g,'');"
            v-model.trim="addOrderparams.customerPrice"
            ref="customerPrice"
          ></el-input>
        </div>
        <div class="item">
          <span>供应商昵称</span>
          <el-autocomplete
            class="inline-input"
            v-model.trim="addOrderparams.supplierName"
            :fetch-suggestions="querySearch"
            placeholder="请输入供应商昵称"
            @select="supplierNameSelect"
            :trigger-on-focus="false"
            popper-class="my-autocomplete"
          >
            <template slot-scope="{ item }">
              <div class="name">{{ item.value }}</div>
              <span class="addr">{{ item.phone }}</span>
            </template>
          </el-autocomplete>
        </div>
        <div class="item">
          <span>电话</span>
          <el-input placeholder="请输入电话" v-model.trim="addOrderparams.supplierTel"></el-input>
        </div>
        <div class="item">
          <span>进价</span>
          <el-input
            placeholder="请输入进价"
            onkeyup="this.value=this.value.replace(/[^\d.]/g,'');"
            v-model.trim="addOrderparams.supplierPrice"
            ref="supplierPrice"
          ></el-input>
        </div>
      </div>
    </div>
    <el-button type="primary" @click="submits" class="sub">提交</el-button>

    <el-table :data="tableData" stripe>
      <el-table-column type="index" label="序号" align="center" width="60"></el-table-column>
      <el-table-column label="图片" align="center">
        <template slot-scope="scope">
          <el-image
            :src="scope.row.order_image"
            fit="cover"
            :preview-src-list="[scope.row.order_image]"
            :onerror="defaultImg2"
            class="tableImg"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="order_size" label="规格" align="center">
        <template slot-scope="scope">
          <el-input v-if="scope.row.editState" v-model="scope.row.order_size"></el-input>
          <p v-if="!scope.row.editState">{{scope.row.order_size}}</p>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="客户" align="center">
        <template slot-scope="scope">
          <div class="useringo">
            <p>{{scope.row.customer_name}}</p>
            <p>{{scope.row.customer_tel}}</p>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="customer_price" align="center" label="价格">
        <template slot-scope="scope">
          <el-input v-if="scope.row.editState" v-model="scope.row.customer_price"></el-input>
          <p v-if="!scope.row.editState">{{scope.row.customer_price}}</p>
        </template>
      </el-table-column>
      <el-table-column prop="name" align="center" label="供应商">
        <template slot-scope="scope">
          <div class="useringo">
            <p>{{scope.row.supplier_name}}</p>
            <p>{{scope.row.supplier_tel}}</p>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="supplier_price" align="center" label="进价">
        <template slot-scope="scope">
          <el-input v-if="scope.row.editState" v-model="scope.row.supplier_price"></el-input>
          <p v-if="!scope.row.editState">{{scope.row.supplier_price}}</p>
        </template>
      </el-table-column>
      <el-table-column prop="order_code" align="center" label="订单号"></el-table-column>
      <el-table-column prop="create_time" align="center" label="时间"></el-table-column>
      <el-table-column prop="name" align="center" label="状态/操作" width="200">
        <template slot-scope="scope">
          <div class="caozuo">
            <div>
              <span>{{scope.row.send_state==1?'已到货':'未到货'}}</span>
              <el-button type="primary" size="mini" @click="repeatOrder(scope.row)">再来一单</el-button>
            </div>
            <div>
              <el-button type="primary" size="mini" @click="edit(scope.row)">{{scope.row.text}}</el-button>
              <el-button type="danger" size="mini" @click="del(scope.row)">删除</el-button>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<style lang='scss'>
.el-autocomplete-suggestion li.highlighted,
.el-autocomplete-suggestion li:hover {
  background: #66b1ff !important;
  color: #fff;
  .addr {
    color: #fff;
  }
}
.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;

    .name {
      text-overflow: ellipsis;
      overflow: hidden;
    }

    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .addr {
      color: #ddd;
    }
  }
}
</style>
<style lang="scss" scoped>
.accooutTs {
  font-size: 14px;
  line-height: 30px;
  text-align: center;
}
.el-image__preview {
  object-fit: cover;
}
.wrap {
  .addImg {
    width: 100%;
    max-width: 1400px;
    background: #f0eff2;
    border-radius: 6px;
    height: 200px;
    margin: 30px auto 0;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    .inpfile {
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
      opacity: 0;
      width: 100%;
    }
    img {
      width: 100px;
      display: block;
      margin: 0 auto;
    }
    p {
      text-align: center;
      color: #999;
      font-size: 14px;
      margin-top: 15px;
    }
  }
  .goodsInfo {
    width: 100%;
    background: #f0eff2;
    border-radius: 6px;
    height: 120px;
    margin: 30px auto 0;
    max-width: 1400px;
    overflow-x: scroll;
    .navListmax {
      min-width: 870px;
      display: flex;
      align-items: center;
      height: 100px;
      justify-content: space-around;
      padding: 0 10px;
    }
    img {
      min-width: 80px;
      min-height: 80px;
      border-radius: 6px;
      border: 1px solid #999;
      object-fit: cover;
      width: 80px;
      height: 80px;
    }
    .item {
      display: flex;
      align-items: center;
      margin-left: 20px;
      flex-direction: column;
      width: 160px;
      span {
        color: #555;
        font-size: 14px;
        display: block;
        margin-bottom: 8px;
      }
      input {
        border: none;
        outline: none;
        border-radius: 20px;
        text-indent: 1em;
        height: 30px;
        color: #555;
      }
    }
  }
  .el-table {
    margin: 0 auto;
  }
  .sub {
    width: 50%;
    margin: 30px auto;
    display: block;
  }
  .tableImg {
    width: 60px;
    height: 60px;
    display: block;
    border-radius: 4px;
    margin: 0 auto;
    object-fit: cover;
  }
  .useringo {
    p {
      text-align: center;
    }
  }
  .caozuo {
    display: flex;
    justify-content: space-around;
    height: 66px;
    .el-button {
      margin-left: 0;
    }
    div {
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      height: 100%;
      span {
        color: #999;
        font-size: 14px;
      }
    }
  }
}
</style>
<script>
import {
  orderList,
  saveOrder,
  upfile,
  delOrder,
  editOrder,
  linkmanList,
  deleteById
} from "../utils/interface";
import cnchar from "cnchar";
import "cnchar-poly";
import {
  compressionRatio,
  convertBase64UrlToBlob,
  photoCompress
} from "../utils/img";
export default {
  data() {
    return {
      tableData: [],
      addImgUrl: "",
      restaurants: null,
      defaultImg2: 'this.src="' + require("../assets/timg.jpg") + '"',
      addOrderparams: {
        orderImage: "",
        orderSize: "",
        customerName: "",
        customerTel: "",
        customerPrice: "",
        supplierName: "",
        supplierTel: "",
        supplierPrice: ""
      },
      type: JSON.parse(localStorage.getItem("userInfo")).account_type
    };
  },
  methods: {
    // 添加图片
    getImg(e) {
      this.changepic();
    },
    // 获取订单列表
    getOrderList() {
      orderList({
        currentPage: 1,
        pageSize: 20
      }).then(res => {
        console.log(res.data.data);
        res.data.data.list.map(item => {
          item.editState = false;
          item.text = "修改";
        });
        this.tableData = res.data.data.list;
      });
    },
    // 提交新增商品
    submits() {
      if (!this.addOrderparams.orderImage) {
        this.$alert("请上传商品图片", "提示", {
          confirmButtonText: "确定"
        });
        return false;
      }
      if (!this.addOrderparams.orderSize) {
        this.$alert("请输入规格", "提示", {
          confirmButtonText: "确定"
        });
        return false;
      }
      if (!this.check(this.addOrderparams.customerName)) {
        this.$alert(
          "请输入正确的客户昵称，支持文字、英文、数字，不支持符号和空格",
          "提示",
          {
            confirmButtonText: "确定"
          }
        );
        return false;
      }
      if (this.addOrderparams.customerTel) {
        if (!/^1[3456789]\d{9}$/.test(this.addOrderparams.customerTel)) {
          this.$alert("请输入正确的电话格式", "提示", {
            confirmButtonText: "确定"
          });
          return false;
        }
      }

      // if (!this.addOrderparams.customerPrice) {
      //   this.$alert("请输入客户价格", "提示", {
      //     confirmButtonText: "确定"
      //   });
      //   return false;
      // }

      if (!this.check(this.addOrderparams.supplierName)) {
        this.$alert(
          "请输入正确的供应商昵称，支持文字、英文、数字，不支持符号和空格",
          "提示",
          {
            confirmButtonText: "确定"
          }
        );
        return false;
      }
      if (this.addOrderparams.supplierTel) {
        if (!/^1[3456789]\d{9}$/.test(this.addOrderparams.supplierTel)) {
          this.$alert("请输入供应商电话", "提示", {
            confirmButtonText: "确定"
          });
          return false;
        }
      }

      // if (!this.addOrderparams.supplierPrice) {
      //   this.$alert("请输入供应商价格", "提示", {
      //     confirmButtonText: "确定"
      //   });
      //   return false;
      // }
      saveOrder(this.addOrderparams).then(res => {
        console.log(res.data.data);
        if (res.data.code == 200) {
          this.$message({
            message: "添加成功",
            type: "success"
          });
          this.getLinkNameList();
        }
        this.getOrderList();
        this.addOrderparams = {
          orderImage: "",
          orderSize: "",
          customerName: "",
          customerTel: "",
          customerPrice: "",
          supplierName: "",
          supplierTel: "",
          supplierPrice: ""
        };
        this.addImgUrl = "";
      });
    },
    // 图片预览
    changepic(copy) {
      const loading = this.$loading({
        lock: true,
        text: "上传中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      var reads = new FileReader();
      var param = new FormData();
      let that = this;
       var f  = null
       if(copy){
         f=copy
       }else{
f = document.getElementById("file").files[
        document.getElementById("file").files.length - 1
      ];
       }
      
      photoCompress(f, {}, function(res) {
        var bl = convertBase64UrlToBlob(res);
        console.log(bl);
        if (bl.size / 1024 / 1024 > 2.2) {
          this.$message({
            type: "error",
            message: "上传商品图片大小不能超过2M"
          });
          return false;
        }
        param.append("file", bl);
        upfile(param).then(res => {
          that.addImgUrl = res.data.data;
          that.addOrderparams.orderImage = res.data.data;
          loading.close();
        });
      });
    },
    // 删除订单
    del(row) {
      this.$confirm("您将删除该订单, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteById({order_id:row.order_id}).then(res => {
            this.getOrderList();
            this.$message({
              type: "success",
              message: "删除成功!"
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 修改订单
    edit(row) {
      console.log(JSON.stringify(row));
      if (row.editState) {
        let data = {
          orderImage: row.order_image,
          orderSize: row.order_size,
          customerName: row.customer_name,
          customerTel: row.customer_tel,
          customerPrice: row.customer_price,
          supplierName: row.supplier_name,
          supplierTel: row.supplier_tel,
          supplierPrice: row.supplier_price,
          orderId: row.order_id
        };
        editOrder(data).then(res => {
          this.getOrderList();
          this.$message({
            type: "success",
            message: "修改成功!"
          });
          row.editState = false;
          row.text = "修改";
        });
      } else {
        row.editState = true;
        row.text = "保存";
      }
    },
    // 再来一单
    repeatOrder(row) {
      this.addImgUrl = row.order_image;
      this.addOrderparams = {
        orderImage: row.order_image,
        orderSize: row.order_size,
        customerName: row.customer_name,
        customerTel: row.customer_tel,
        customerPrice: row.customer_price,
        supplierName: row.supplier_name,
        supplierTel: row.supplier_tel,
        supplierPrice: row.supplier_price
      };
    },
    //
    check(v) {
      var regex = new RegExp(
        "^([\u4E00-\uFA29]|[\uE7C7-\uE7F3]|[a-zA-Z0-9_]){1,20}$"
      );
      var res = regex.test(v);
      return res;
    },
    // 获取联系人列表
    getLinkNameList() {
      linkmanList().then(res => {
        let arr = [];
        res.data.data.map(item => {
          var value = item.linkman_name;
          var eng = cnchar
            .spell(item.linkman_name, "first", "low")
            .toLowerCase();
          var eng2 = cnchar.spell(item.linkman_name, "low").toLowerCase();
          arr.push({
            value: value,
            eng: eng,
            tel: item.tel,
            eng2: eng2,
            phone: item.tel
          });
        });
        this.restaurants = arr;
      });
    },
    // 联想
    querySearch(queryString, cb) {
      console.log(queryString);
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      cb(results);
    },
    createFilter(queryString) {
      if (/^[a-zA-Z]*$/.test(queryString)) {
        console.log(queryString.toLowerCase());

        return restaurant => {
          console.log(restaurant);
          return (
            restaurant.eng2.toLowerCase().indexOf(queryString.toLowerCase()) !==
              -1 ||
            restaurant.eng.toLowerCase().indexOf(queryString.toLowerCase()) !==
              -1
          );
        };
      } else if (/^[\u4e00-\u9fa5]*$/.test(queryString)) {
        return restaurant => {
          return (
            restaurant.value
              .toLowerCase()
              .indexOf(queryString.toLowerCase()) !== -1
          );
        };
      } else {
        return restaurant => {
          return (
            restaurant.value
              .toLowerCase()
              .indexOf(queryString.toLowerCase()) === 0
          );
        };
      }
    },
    // 点击联想词 客户
    customerNameSelect(e) {
      console.log(e);
      this.addOrderparams.customerTel = e.tel;
      this.$refs.customerPrice.$el.querySelector("input").focus();
    },
    // 点击联想词 供应商
    supplierNameSelect(e) {
      this.addOrderparams.supplierTel = e.tel;
      this.$refs.supplierPrice.$el.querySelector("input").focus();
    },
    indexMethod(index) {
      console.log(index);
      return this.tableData.length - index;
    },
    docopy() {
      let that = this
      document.addEventListener("paste", function(event) {
        var items = (event.clipboardData || window.clipboardData).items;
        var file = null;
        if (items && items.length) {
          // 搜索剪切板items
          for (var i = 0; i < items.length; i++) {
            if (items[i].type.indexOf("image") !== -1) {
              file = items[i].getAsFile();
              break;
            }
          }
          if (file) {
            console.log(file, "粘贴的图片");
            that.changepic(file)
            return;
          }
        }
      });
    }
  },
  mounted() {
    this.getOrderList();
    this.getLinkNameList();
    this.docopy()
    console.log(this.type);
  }
};
</script>